﻿// 注意 background文件里的log语句不会执行!
// console.log(' background ！');

let currentPageInfo = {};


// 监听来自content script的消息
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    // 如果消息是要求关闭Vue选项卡
    if (message.closeVueTab) {
        // 获取所有当前打开的标签页
        chrome.tabs.query({}, (tabs) => {
            console.log('标签页: ', tabs);
          // 遍历标签页
          tabs.forEach((tab) => {
            // 如果标签页的标题包含"Vue Devtools"，则关闭该标签页
            if (tab.title.includes("Vue")) {
              chrome.tabs.remove(tab.id);
            }
          });
        });
      }

    if (message.action === "saveUserInput") {
        let imgListArr = message.imgList;
        let domText = message.domText

        if (imgListArr || domText) {
            processUserInput(imgListArr, domText, currentPageInfo);
            sendResponse({success:true}); // 将结果发送回去
        } else {
            sendResponse({success:false})
        }
    }
});


function GetMessageFromPopup(data) {
    console.log("popup ~~", data)
}


function sendMessageToContentScript(message, callback) {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
            if (callback) callback(response);
        });
    });
}



function trim(str) { //删除左右两端的空格
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
function removeURLParameters(url) {
    try {
        var urlObject = new URL(url);
        urlObject.search = '';
        return urlObject.toString();
    } catch (error) {
        console.error('Error parsing URL:', error);
        return url;
    }
}



// 将字符串类型的 DOM 转换为 DOM 元素
function parseHTMLString(htmlString) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(htmlString, 'text/html');
    return doc.body;
}


// 异步函数，用于获取当前标签页信息
async function getCurrentTabInfo() {
    return new Promise(function (resolve, reject) {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            if (tabs.length > 0) {
                var currentTab = tabs[0];

                var pageInfo = {
                    url: currentTab.url,
                    title: currentTab.title
                };
                resolve(pageInfo);
            } else {
                reject(new Error('无法获取当前标签页信息。'));
            }
        });
    });
}

function getDateStr(params) {
    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth() + 1; // 月份从0开始，需要加1
    var date = today.getDate();
    var hours = today.getHours();
    var minutes = today.getMinutes();

    // 格式化时分，确保是两位数
    var formattedHours = hours < 10 ? '0' + hours : hours;
    var formattedMinutes = minutes < 10 ? '0' + minutes : minutes;


    var folderName = year + '-' + month + '-' + date + '-' + formattedHours + '' + formattedMinutes;

    return folderName;

}
